package com.baoyouqun.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web配置类，用于配置静态资源映射
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${file.storage.base-path}")
    private String basePath;

    @Value("${file.storage.url-prefix}")
    private String urlPrefix;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射文件访问路径
        // 例如: http://localhost:8080/files/xxx/xxx.jpg 映射到本地路径 /opt/local-storage/files/xxx/xxx.jpg
        String resourcePattern = urlPrefix.replace("http://localhost:8080", "") + "**";
        registry.addResourceHandler(resourcePattern)
                .addResourceLocations("file:" + basePath + "/");
    }


    // 注册请求日志过滤器
    @Bean
    public FilterRegistrationBean<RequestLoggingFilter> requestLoggingFilter() {
        FilterRegistrationBean<RequestLoggingFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new RequestLoggingFilter()); // 设置自定义过滤器
        registrationBean.addUrlPatterns("/*"); // 拦截所有请求
        registrationBean.setOrder(1); // 过滤器执行顺序（数字越小越先执行）
        return registrationBean;
    }
}
